from django.shortcuts import render
from django.views import View
from django.http import JsonResponse
from rest_framework_jwt.settings import api_settings

from user.models import SysUser  # 包没有导入
from rest_framework import serializers

# Create your views here.

class TestUserView(View):
    def get(self, request):
        token = request.META.get('HTTP_AUTHORIZATION')
        print("token", token)
        if token is not None and token != '':
            user_list = SysUser.objects.all()
            print(user_list, type(user_list))
            # 把对象类型转换为字典类型
            user_dict = user_list.values()
            print(user_dict, type(user_dict))
            # 解析字典类型 把字典类型转换为json串
            userList = list(user_dict)
            print(userList, type(user_list))
            # 响应给前台json串的数据
            return JsonResponse({'code': 200, 'info': '测试成功', 'data': userList})
            # 通过网页访问 localhost：5000/user/test
        else:
            return JsonResponse({'code': 200, 'info': '未授权没有访问权限'})


class JwtTestView(View):
    def get(self, request):
        user = SysUser.objects.get(username="admin", password="123456")
        # jwt 处理函数
        jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        # 生成载荷的令牌
        # 把用户对象传递，获取该对象的属性值
        payload = jwt_payload_handler(user)
        # 将jwt获取的属性值 编译成json格式
        token = jwt_encode_handler(payload)
        print('token', token)
        return JsonResponse({'code': 200, 'info': '获取成功', 'token': token})


# 登录操作
class LoginView(View):
    def post(self, request):
        username = request.GET.get('username')
        password = request.GET.get('password')
        try:
            user = SysUser.objects.get(username=username, password=password)
            # user_dict = user.values()
            # # 解析字典类型 把字典类型转换为json串
            # userList = list(user_dict)
            # print(userList)
            jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            # 生成载荷的令牌
            # 把用户对象传递，获取该对象的属性值
            payload = jwt_payload_handler(user)
            # 将jwt获取的属性值 编译成json格式
            token = jwt_encode_handler(payload)
        except Exception as e:
            print(e)
            return JsonResponse({'code': 500, 'info': '用户名或密码错误'})

        return JsonResponse({'code': 200, "token": token, "user": SysUserSerializers(user).data, 'info': '登录成功'})


class SysUserSerializers(serializers.ModelSerializer):
    class Meta:
        model = SysUser
        fields = '__all__'

